package com.jds.test.httpproxy.miniserver;

import com.alibaba.fastjson.JSONObject;
import com.jds.test.httpproxy.httpclient.OriginHttp;
import com.jds.test.httpproxy.httpclient.ReqQueue;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by sunyuming on 18/8/30.
 */
public class RequestToBodyDecoder extends MessageToMessageDecoder<FullHttpRequest> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("active");
        super.channelActive(ctx);
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest, List<Object> list) throws Exception {

        HttpMethod httpMethod = fullHttpRequest.getMethod();
        String uri = fullHttpRequest.getUri();
        HttpHeaders httpHeaders = fullHttpRequest.headers();

        Map<String, String> map = new HashMap<>();
        for (Map.Entry<String, String> entry : httpHeaders.entries()) {
            map.put(entry.getKey(), entry.getValue());
        }

        ByteBuf msg = fullHttpRequest.content();
        byte[] bs = new byte[msg.readableBytes()];
        msg.readBytes(bs);

        OriginHttp originHttp = new OriginHttp(httpMethod.name(), uri, map, bs, channelHandlerContext);
        ReqQueue.put(originHttp);

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        super.exceptionCaught(ctx, cause);
    }
}
